package com.xzq.bugstack;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/19 11:37
 * @Version 1.0.0
 **/
public class ServerHandler extends ChannelInboundHandlerAdapter{

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //当有客户端连接后，添加到channelGroup通信组
        ChannelHandler.channelGroup.add(ctx.channel());

        //日志
        SocketChannel sc = (SocketChannel) ctx.channel();
        System.out.println("建立连接.....");
        System.out.println("连接IP: "+sc.localAddress().getHostString());
        System.out.println("连接端口: " + sc.localAddress().getPort());

        //向客户端发送消息
        String str = "已加入群聊 ";
        ctx.writeAndFlush(str);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端断开连接...." + ctx.channel().localAddress().toString());
        //当有客户端退出后，从channelGroup中移除
        ChannelHandler.channelGroup.remove(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "接收到信息: " + msg);

        //群发客户端
        ChannelHandler.channelGroup.writeAndFlush(msg);
    }
}
